// pages/index/index.js
var util = require('../../utils/util.js');
var api = require('../../config/api.js');

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */

  data: {
    OwnerOrPassengerRelease: wx.getStorageSync('OwnerOrPassengerRelease') || 'owner',
    StatusBar: 20,
    timeList: ['明天', '后天', '可接', '包送'],
    active: null,
    ReleaseList: [],
    refresher: true,
    triggered: true,
    InTheEnd: false,
    InTheLoading: false,
    TheCurrentOorder: [],
    getAddrea: '0',
    setOut: {},
    currentLocation: {},
    TravelHeight: 0,
    loginshow: false,
    showPrivacy: false,
    Leftshow: false,
    tailNumber: '',
    city: '',
    pageSize: 0,
    Swiperlist: [],
    notices: [],
    animationData: {},
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      StatusBar: app.globalData.StatusBar,
      OwnerOrPassengerRelease: wx.getStorageSync('OwnerOrPassengerRelease') || 'owner'
    })
    if (options.passenger) {
      this.setData({
        OwnerOrPassengerRelease: 'passenger'
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    try {
      wx.pageScrollTo({
        scrollTop: 0, // 滚动到页面的顶部
        // duration: 300 // 滚动动画的时长，单位为毫秒
      });
      if (this.data.Leftshow) {
        wx.hideLoading()
        wx.stopPullDownRefresh();
      }
      const accountInfo = wx.getAccountInfoSync();
      this.setData({
        version: accountInfo.miniProgram.version
      })
      let token = wx.getStorageSync('TwoPlusTravel') || {}
      console.log(token);
      if (Object.keys(token).length == 0) {
        this.setData({
          loginshow: true,
          tailNumber: '',
          TheCurrentOorder: []
        })
      } else {
        this.setData({
          loginshow: false,
          tailNumber: token.phone.slice(-4)
        })
      }
      this.getLocation()
      this.getTheCurrentItinerary()
    } catch (error) {

    }
  },
  GoToLogin() {
    wx.navigateTo({
      url: '/pages/subpackage/wxlogin/index',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.data.Leftshow) {
      wx.stopPullDownRefresh();
      return;
    }
    this.setData({
      InTheLoading: true
    })
    this.bindrefresherrefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.LoadingMerchantsData()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 获取发布列表
  getReleaseList() {
    try {
      let that = this
      let types = this.data.OwnerOrPassengerRelease == 'owner'
      let data = {
        latitude: app.globalData.position.latitude, // 经纬度
        longitude: app.globalData.position.longitude,
        type: this.data.pageSize,
        phone: wx.getStorageSync('TwoPlusTravel').phone
      }
      util.request('GET', !types ? api.getScheduleList : api.getUserScheduleList, data).then(function (res) {
        wx.hideLoading()
        wx.stopPullDownRefresh()
        let list = res.data || []
        list.forEach((item) => {
          item.godate = util.timeChangeover(item.godate)
          item.distance = item.distance > 10 ? Math.floor(item.distance) : item.distance
        })
        if (list != null && !list.length) {
          that.setData({
            InTheEnd: true
          })
        }
        if (that.data.pageSize > 0) {
          list = [...that.data.ReleaseList, ...list]
        }
        that.setData({
          ReleaseList: list,
          InTheLoading: false
        })
      })
    } catch (error) {
      console.log(error);
    }
  },
  // 分类筛选
  ClassificationScreening(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      active: this.data.active == index ? null : index
    })
    wx.showLoading({
      title: '加载中~',
    })
    this.getReleaseList()
  },
  // 下拉刷新
  bindrefresherrefresh() {
    let time = setTimeout(() => {
      this.setData({
        refresher: true,
        triggered: false,
        getAddrea: '0',
        InTheEnd: false,
        pageSize: 0
      })
      wx.stopPullDownRefresh()
      this.getNotice()
      this.getLocation()
      this.getTheCurrentItinerary()
      clearTimeout(time)
    }, 1000)
  },
  // 上滑加载更多
  LoadingMerchantsData() {
    if (this.data.InTheEnd || this.data.InTheLoading) {
      return
    }
    this.setData({
      pageSize: this.data.pageSize + 1
    })
    wx.showLoading({
      title: '加载中~'
    })
    this.getReleaseList()
  },
  // 行程取消
  TheTripCancelled(e) {
    let that = this
    let item = e.currentTarget.dataset.id
    let isWithinOneHour = util.isWithinOneHour(item.godate)
    wx.showModal({
      title: '提示',
      content: isWithinOneHour ? '行程即将开始，若取消行程需扣违约金' : '是否确认取消行程',
      success(res) {
        if (res.confirm) {
          that.postcancelPassenger(item.id)
        }
      }
    })
  },
  // 乘客发布的行程取消
  PassengerTravelCancelled(e) {
    let that = this
    let item = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '是否确定取消发布的行程',
      success(res) {
        if (res.confirm) {
          that.postcancelPassengerPassenger(item.details_id)
        }
      }
    })
  },
  // 行程确认
  TravelConfirmation(e) {
    let that = this
    let item = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: item.details_update_by == 1 ? '行程确认上车' : '行程确认到达',
      success(res) {
        if (res.confirm) {
          let data = {
            id: item.id,
            phone: wx.getStorageSync('TwoPlusTravel').phone,
            latitude: app.globalData.position.latitude, // 经纬度
            longitude: app.globalData.position.longitude,
          }
          if (item.details_update_by == 1) {
            that.PassengersCBus(data)
          } else {
            that.PassengersConfirmArrival(data)
          }
        }
      }
    })
  },
  // 乘客确认上车
  PassengersCBus(data) {
    let that = this
    util.request('POST', api.postcarConfirm, data).then(function (res) {
      console.log(res);
      if (res.code == 200) {
        wx.showToast({
          title: '确认成功！',
        })
        that.getTheCurrentItinerary()
      } else {
        wx.showToast({
          title: '行程异常~',
          icon: 'error'
        })
      }
      wx.hideLoading()
    })
  },
  // 乘客确认到达
  PassengersConfirmArrival(data) {
    let that = this
    util.request('POST', api.TheTripCancelArrive, data).then(function (res) {
      console.log(res);
      switch (res.code) {
        case 100:
          wx.showToast({
            title: '数据异常！',
            icon: 'error'
          })
          break;
        case 101:
          wx.showToast({
            title: '行程未出发，无法点击到达',
            icon: 'none'
          })
          break;
        case 200:
          wx.showToast({
            title: '确认成功 行程结束',
            icon: 'none'
          })
          break;
        case 300:
          wx.showToast({
            title: '订单数据异常',
            icon: 'none'
          })
          break;
        case 301:
          wx.showToast({
            title: '请先确定上车',
            icon: 'none'
          })
          break;
        default:
          wx.showToast({
            title: '行程异常~',
            icon: 'error'
          })
          break;
      }
      that.getTheCurrentItinerary()
      wx.hideLoading()
    })
  },
  // 司机
  driverConfirmation(e) {
    this.getLocation()
    let that = this
    let item = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: item.update_by == 1 ? '行程确认出发' : '行程确认到达',
      success(res) {
        if (res.confirm) {
          let data = {
            id: item.id,
            phone: wx.getStorageSync('TwoPlusTravel').phone,
            latitude: app.globalData.position.latitude,
            longitude: app.globalData.position.longitude
          }
          if (item.update_by == 1) {
            that.TheTripSetOut(data)
          } else {
            that.TheTripCarArrive(data)
          }
        }
      }
    })
  },
  // 司机出发
  TheTripSetOut(data) {
    let that = this
    util.request('POST', api.TheTripSetOut, data).then(function (res) {
      if (res.code == 200) {
        wx.showToast({
          title: '行程已确认出发',
          icon: 'none'
        })
        that.getTheCurrentItinerary()
      } else {
        wx.showToast({
          title: '数据异常',
          icon: 'none'
        })
      }
      wx.hideLoading()
    })
  },
  // 司机到达
  TheTripCarArrive(data) {
    let that = this
    util.request('POST', api.TheTripCarArrive, data).then(function (res) {
      switch (res.code) {
        case '100':
          wx.showToast({
            title: '行程异常',
            icon: 'none'
          })
          break;
        case 200:
          wx.showToast({
            title: '行程已确认到达',
            icon: 'none'
          })
          break;
        case 300:
          wx.showToast({
            title: '离目的地距离太远，无法结束行程',
            icon: 'none'
          })
          break;
        case 400:
          wx.showToast({
            title: '数据写入异常，请联系管理员',
            icon: 'none'
          })
          break;
        default:
          break;
      }
      that.getTheCurrentItinerary()
      wx.hideLoading()
    })
  },

  //乘客
  postcancelPassengerPassenger(e) {
    let that = this
    let item = e
    if (item.update_by == 2) {
      wx.showToast({
        title: '该行程正在进行中~',
        icon: 'none'
      })
      return
    }
    let data = {
      id: item,
      phone: wx.getStorageSync('TwoPlusTravel').phone
    }
    util.request('POST', api.postcancelPassenger, data).then(function (res) {
      console.log(res);
      if (res.code == 200) {
        wx.showToast({
          title: '取消成功！',
        })
      } else {
        wx.showToast({
          title: '行程异常~',
          icon: 'error'
        })
      }
      that.setData({
        pageSize: 0
      })
      that.getTheCurrentItinerary()
      that.getReleaseList()
      wx.hideLoading()
    })
  },

  // 行程取消
  postcancelPassenger(e) {
    let that = this
    let item = e
    if (item.update_by == 2) {
      wx.showToast({
        title: '该行程正在进行中~',
        icon: 'none'
      })
      return
    }
    let data = {
      id: item,
      phone: wx.getStorageSync('TwoPlusTravel').phone
    }
    util.request('POST', api.postdrivercancelPassenger, data).then(function (res) {
      console.log(res);
      if (res.code == 200) {
        wx.showToast({
          title: '取消成功！',
        })
      } else {
        wx.showToast({
          title: '行程异常~',
          icon: 'error'
        })
      }
      that.setData({
        pageSize: 0
      })
      that.getTheCurrentItinerary()
      that.getReleaseList()
      wx.hideLoading()
    })
  },

  //====================================新修改的查看行程20250328===========start==================================
  ViewTheTrip(e) {
    console.log(e);
    let item = e.currentTarget.dataset.id
    console.log("itemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitem");
    console.log(item);
    console.log("itemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitem");
    // debugger
    if (!item.seat && item.phone && item.class == 1) { //乘客已接单，支付了去行程页
      wx.navigateTo({
        url: `/pages/subpackage/DetailsOfTheTrip/index?id=${item.id}&role=2&isPay=${item.class}&detailsUpdateBy=${item.details_update_by}&goodsUpdateBy=${item.goods_update_by}&detailsId=${item.details_id}`,
      })
      return
    } else if (item.seat) { //车主，已接单，去行程页
      wx.navigateTo({
        url: `/pages/subpackage/DetailsOfTheTrip/index?id=${item.id}&role=1`,
      })
      return
    } else {
      wx.navigateTo({
        url: `/pages/subpackage/DetailsPassengerTravel/index?id=${item.id}&detailsId=${item.details_id}`,
      })
      return
    }
  },
  //====================================新修改的查看行程20250328===========old==================================

  //查看行程
  ViewTheTripOld(e) {
    console.log(e);
    let item = e.currentTarget.dataset.id
    console.log("itemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitem");
    console.log(item);
    console.log("itemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitem");
    // debugger
    // 乘客发布
    if (item.codeRole == 2 && item.goods_user_id == null) {
      wx.navigateTo({
        // url: '/pages/subpackage/DetailsPassengerTravel/index?id=' + item.id + '&role=1',
        // url: '/pages/subpackage/passengerTravel/index?id=' + item.id + '&role=1&detailsId='+item.details_id,
        url: '/pages/subpackage/DetailsPassengerTravel/index?id=' + item.id + '&role=2' + '&detailsId=' + item.details_id,

      })
      return
    }


    // 未支付
    //role 2 乘客
    // details_update_by: 5 乘客订单状态（有这个值的肯定是乘客）
    // class 是否支付 0 未支付  1 支付
    // goods_update_by: 1 车主行程状态
    //跳转到乘客，TheTripInitiated（下单页）
    // if (item.details_update_by == 5) {
    //   wx.navigateTo({
    //     url: `/pages/subpackage/TheTripInitiated/index?id=${item.id}&unpaid=1&role=2&isPay=${item.class}&detailsUpdateBy=${item.details_update_by}&goodsUpdateBy=${item.goods_update_by}&detailsId=${item.details_id}`, 
    //   })
    //   return
    // }


    // 详情
    // 车主要跳转的非地图页（行车页）
    // if (!item.details_update_by) {
    wx.navigateTo({
      url: `/pages/subpackage/DetailsOfTheTrip/index?id=${item.id}&role=1&isPay=${item.class}&detailsUpdateBy=${item.details_update_by}&goodsUpdateBy=${item.goods_update_by}&detailsId=${item.details_id}`,
    })
    // }

  },

  onClose() {
    this.setData({
      show: !this.data.show,
    })
  },
  onLeftClose() {
    this.setData({
      Leftshow: false
    })
  },
  // 授权获取地理位置
  getLocation() {
    let that = this
    that.setData({
      showPrivacy: false
    })
    wx.getLocation({
      type: 'gcj02', //表示使用GPS定位
      success: (res) => {
        app.globalData.position.latitude = res.latitude;
        app.globalData.position.longitude = res.longitude;
        that.setData({
          getAddrea: '1',
          pageSize: 0,
          InTheEnd: false
        })
        // wx.showLoading({
        //   title: '加载中~'
        // })
        that.getReleaseList()
        that.getNotice()
      },
      //表示用户没有开启授权
      fail: (res) => {
        console.log(res);
        wx.showToast({
          title: '已取消定位,授权定位服务',
          icon: 'none'
        })
        let timer = setTimeout(() => {
          wx.showModal({
            title: '',
            confirmColor: '#b4282d',
            content: '需要获取地理位置 请确认授权',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    if (!res.authSetting['scope.userLocation']) {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'error'
                      })
                    }
                  },
                  fail(res) {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'error'
                    })
                  }
                })
              }
            }
          })
          clearTimeout(timer)
        }, 1000)
      }
    })
  },
  // 获取公告轮播图
  getNotice() {
    let that = this
    let data = {
      "identity": this.data.OwnerOrPassengerRelease == 'owner' ? "2" : '1', // 身份1 乘客   2车主
      "latitude": app.globalData.position.latitude, // 经纬度
      "longitude": app.globalData.position.longitude,
    }
    try {
      util.request('POST', api.getNotice, data).then(function (res) {
        that.setData({
          notices: res.notice,
          Swiperlist: res.advertisement
        })
        // that.startAnimation();
      })
    } catch (error) {

    }
  },
  startAnimation() {
    var that = this;
    var animation = wx.createAnimation({
      duration: 1000, // 动画持续时间
      timingFunction: 'linear' // 动画效果
    })
    // this.animation = animation

    var count = 0;
    var timer = setInterval(function () {
      animation.translateY(-50).step() // 向上移动50px
      that.setData({
        animationData: animation.export()
      })
      count++;
      if (count == that.data.notices.length) {
        count = 0;
        // 重置位置
        animation.translateY(0).step()
        that.setData({
          animationData: animation.export()
        })
      }
    }, 2000) // 滚动间隔时间
  },
  // 获取当前行程
  getTheCurrentItinerary() {
    let that = this
    let phone = wx.getStorageSync('TwoPlusTravel').phone || ''
    if (!phone) {
      return
    }

    util.request('GET', api.getTheCurrentItinerary, {
      phone: phone
    }).then(function (res) {
      let TheCurrentOorder = []
      let driver = res.driver // 司机
      let passenger = res.passenger // 乘客
      if (driver.code == 101 || passenger.code == 101) {
        wx.showToast({
          title: '行程状态异常',
          icon: 'error'
        })
      }
      if (driver.code == 200) {
        driver.time = util.timeChangeover(driver.godate)
        TheCurrentOorder.push(driver)
      }

      if (passenger.code == 200) {
        passenger.time = util.timeChangeover(passenger.godate)
        TheCurrentOorder.push(passenger)
      }
      let reversedArr = []
      // 时间比较 换位置 时间短放前面
      if (TheCurrentOorder.length > 1) {
        let godate = new Date(TheCurrentOorder[0].godate)
        let godate2 = new Date(TheCurrentOorder[1].godate)
        let reversingPosition = godate <= godate2
        if (!reversingPosition) {
          reversedArr = [].concat(TheCurrentOorder).reverse();
        }
      }
      that.setData({
        TheCurrentOorder: reversedArr.length ? reversedArr : TheCurrentOorder
      })
      let time = setTimeout(() => {
        that.getSchooltimeHeight()
        clearTimeout(time)
      }, 0);
    })
  },
  // 发布行程
  ReleaseSchedule(e) {
    let setOut = e.detail.setOut
    let destination = e.detail.destination
    if (setOut.name && destination.name) {
      this.setData({
        setOut: setOut,
        destination: destination,
        show: true
      })
    }
  },
  MyScheduleOrder() {
    if (this.data.loginshow) {
    //   wx.showToast({
    //     title: '请点击下方 前往登录',
    //     icon: 'none'
    //   })
    wx.showToast({
            title: '未登录 前往登录中~',
            icon: 'none',
            duration: 1500
          })
          let time = setTimeout(() => {
            wx.navigateTo({
              url: '/pages/subpackage/wxlogin/index'
            })
            clearTimeout(time)
          }, 1500)
        //   登录修改end
      return
    }
    this.setData({
      Leftshow: true
    })
    // let token = wx.getStorageSync('TwoPlusTravel') || {}
    // if (Object.keys(token).length == 0) {
    //   wx.showToast({
    //     title: '未登录 请点击下方按钮前往登录',
    //     icon: 'none',
    //     duration: 1500
    //   })
    //   return
    // }
    // wx.navigateTo({
    //   url: '/pages/subpackage/ScheduleRrder/index'
    // })
  },
  placeOfDeparture(e) {
    let data = e.detail
    let city = e.detail.city
    delete data.city
    this.setData({
      currentLocation: data,
      city: city
    })
  },

  // 跳转到接单详情页
  GoToridesharing(e) {
    console.log("itemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitemitem");
    // debugger
    let id = e.currentTarget.dataset.id
    let detailsId = e.currentTarget.dataset.detailsid
    let token = wx.getStorageSync('TwoPlusTravel') || {}
    // if (Object.keys(token).length == 0) {
    //   wx.showToast({
    //     title: '未登录 请点击下方按钮前往登录',
    //     icon: 'none',
    //     duration: 1500
    //   })
    //   return
    // }
    let types = this.data.OwnerOrPassengerRelease == 'owner'
    // 查看当前是否有行程
    let TheCurrentOorder = this.data.TheCurrentOorder
    let items = TheCurrentOorder.filter((item) => item.id == id)
    // debugger
    // 车主前往乘客发布的详情
    console.log(types);
    if (types) {
        console.log("车主查看乘客订单列表");
      wx.navigateTo({
        url: '/pages/subpackage/DetailsPassengerTravel/index?id=' + id + '&role=1' + '&detailsId=' + detailsId,
        // url: '/pages/subpackage/passengerTravel/index?id=' + id + '&role=1',
      })
      return
    } else {
        console.log("乘客查看车主行程列表");
        console.log(items);
        
      // 有行程
      if (items.length) {
          
        let role = 0
        // 是车主 直接进入行程车主详情页
        if (items[0].seat) {
          role = 1
          wx.navigateTo({
            url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + id + '&role=' + role,
          })
          return
        }
        // 乘客详情
        if (items.class) {
          wx.navigateTo({
            url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + id + '&role=' + role + '&detailsId=' + detailsId,
          })
          return
        } else {
          // 乘客进入乘客发布的行程
          wx.navigateTo({
            url: `/pages/subpackage/TheTripInitiated/index?id=${id}&nonpayment=1` + '&detailsId=' + detailsId,
          })
        }
      }
      // 没有当前行程 直接进入行程-合乘页(乘客？)
      wx.navigateTo({
        url: '/pages/subpackage/TheTripInitiated/index?id=' + id + '&role=2',
      })
    }
  },
  // 调起手机拨号
  dialANumber(e) {
    let num = e.currentTarget.dataset.num
    wx.makePhoneCall({
      phoneNumber: num
    })
  },
  getSchooltimeHeight() {
    const query = wx.createSelectorQuery();
    query.select('.TheCurrentOorder').boundingClientRect(rect => {
      if (rect) {
        this.setData({
          TravelHeight: rect.height * 2
        });
      }
    }).exec();
  },
  gotoNavCon(e) {
    let index = e.currentTarget.dataset.index
    let token = wx.getStorageSync('TwoPlusTravel') || {}
    if (Object.keys(token).length == 0 && (index == '1' || index == '2' || index == '5')) {
      wx.showToast({
        title: '未登录 请前往登录',
        icon: 'none',
        duration: 1500
      })
      return
    }
    switch (index) {
      case '1':
        wx.navigateTo({
          url: '/pages/subpackage/withdrawDeposit/index'
        })
        break;
      case '2':
        wx.navigateTo({
          url: '/pages/subpackage/ScheduleRrder/index'
        })
        break;
      case '3':
        wx.navigateTo({
          url: '/pages/components/platformRules/index'
        })
        break;
      case '4':
        wx.navigateTo({
          url: '/pages/subpackage/contactUs/index'
        })
        break;
      case '5':
        console.log('设置');
        wx.navigateTo({
          url: '/pages/subpackage/intercalate/index'
        })
        break;
      default:
        break;
    }
  },
  SwitchIdentity(e) {
    wx.setStorageSync('OwnerOrPassengerRelease', e.detail)
    this.setData({
      OwnerOrPassengerRelease: e.detail,
      getAddrea: '0',
      InTheEnd: false,
      pageSize: 0
    })
    wx.showLoading({
      title: '加载中~'
    })
    this.getNotice()
    this.getReleaseList()
  }
})